﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Tools;

namespace Pixysoft.Weblications.Sango
{
    class PkHelper
    {
        private static object syncRoot = new Object();

        static double last_sequence = -1;

        private static int counter = 0;

        private static bool fake = false;

        public static string UserCode()
        {
            return Generator_21_id("UR");
        }

        public static string PrimaryCode()
        {
            return Generator_21_id("PK");
        }

        public static string SettingCode()
        {
            return Generator_21_id("ST");
        }

        internal static string BillCode()
        {
            return Generator_21_id("BL");
        }

        public static string LogCode()
        {
            return Generator_21_id("LG");
        }

        public static string Generator_21_id(string moduleId)
        {
            lock (syncRoot)
            {

                StringBuilder buffer = new StringBuilder();
                buffer.Append(SettingHelper.ServerId);
                buffer.Append(moduleId);

                counter++;

                if (fake)
                {
                    buffer.Append(StringCoder.AddZero(counter.ToString(), 16));
                }
                else
                {
                    // 9 digits

                    double current_sequence = GetTime();

                    buffer.Append(current_sequence);

                    buffer.Append(StringCoder.AddZero(counter.ToString(), 6));

                    if (last_sequence > 0 && current_sequence != last_sequence && counter > 10000)
                    {
                        counter = 0;
                    }
                    last_sequence = current_sequence;

                }
                return buffer.ToString();
            }
        }

        private static double GetTime()
        {
            double timesequence = GlobalTimer.Instance.ToTimeSequence();
            return Math.Round(timesequence / 1000);
        }

        private void test()
        {
            Console.WriteLine(Generator_21_id("fk"));
            Console.WriteLine(Generator_21_id("fk").Length);
            for (int i = 0; i < 100000; i++)
            {
                Console.WriteLine(Generator_21_id("fk"));
            }
        }

        private void etst2()
        {
            for (int i = 0; i < 1000; i++)
            {
                Console.WriteLine(GlobalTimer.Instance.GetUniqueSequence());
            }
        }

    }
}
